import moment from "moment";

export const formatTimeInCountDown = (expirationDate: any, domName: any) => {
  if (expirationDate && document.querySelector(domName)) {

    function updateCountdown() {
      // 截止日期
      const cutTime: any = moment(expirationDate)
      // 当前时间
      const currentTime: any = moment();

      // 计算剩余时间
      const duration = moment.duration(cutTime - currentTime);

      // 提取剩余的天数、小时和秒
      const days = Math.floor(duration.asDays()+1);
      const hours = duration.hours();
      const minutes = duration.minutes();
      const seconds = duration.seconds();

      // 格式化为所需的字符串
      const formattedTime = `申报中：剩余${days}天${hours}小时${minutes}分${seconds}秒`;

      // 更新页面上的剩余时间
      if (document.querySelector(domName)) {
        document.querySelector(domName).innerText = formattedTime;
      }

// 每秒更新一次剩余时间
    const countdownInterval = setInterval(updateCountdown, 1000);
      // 如果过期时间已经到达，停止倒计时
      if (duration.asMilliseconds() <= 0) {
        clearInterval(countdownInterval);
        document.querySelector(domName).textContent = "已截止："+new Date(+new Date(cutTime) + 8 * 3600 * 1000).toISOString().replace(/T/g, ' ').replace(/\.[\d]{3}Z/, '');
      }
    }

    // 初始更新剩余时间
    updateCountdown();


  }
}
